package com.lovemanai.tools.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


/**
 * jdbc工具，返回一个Connection对象
 * 实现原理：读取配置文件读取四大参数，创建Connection对象
 * @version 1.0
 * @author lovemanai
 *
 */
public class JdbcUtils_version1_0 {
	
	private static Properties p = null;
	
	/*
	 * 静态初始化
	 * 读取配置文件和注册驱动在获得连接期间只需要执行一次
	 */
	static {
		
		//读取配置文件到输入流
		InputStream in = JdbcUtils_version1_0.class.getClassLoader().getResourceAsStream("dbconfig.properties");
		p = new Properties();
		try {
			//加载配置输入流
			p.load(in);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		try {
			//注册驱动
			Class.forName(p.getProperty("driver"));
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
		
	}
	
	
	public static Connection getConnection() throws SQLException {
		//获得连接
		Connection conn = DriverManager.getConnection(p.getProperty("url"),
				p.getProperty("user"),
				p.getProperty("password"));
		return conn;
	}
}
